<template>
  <div class="app-container">
    <div class="cardbg">
      <div class="card">

        <el-row style="height: 30px;" align="middle">
          <div style="width: 6px; height:20px;background-color:#2984f8;border-radius: 5px;margin-right: 10px;">
          </div>
          <span style="font-size: 18px;">居民管理</span>
        </el-row>
        <!-- 筛选项 -->


        <el-form :model="userqueryParams" size="large" :inline="true" label-width="68px">
          <el-form-item label="签约状态" style="width: 20%;">
            <el-select v-model="userqueryParams.status" placeholder="请选择" clearable>
              <el-option v-for="dict in status" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="签约机构">
            <el-input v-model="userqueryParams.institution" placeholder="请输入签约机构" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="医生团队">
            <el-input v-model="userqueryParams.team" placeholder="请输入医生团队" clearable @keyup.enter="handleQuery" />
          </el-form-item>
          <el-button type="primary" plain icon="Plus" @click="handleAdd"
            v-hasPermi="['resident:resident:add']">新增居民档案</el-button>
          <el-button type="warning" plain icon="Download" @click="handleExport"
            v-hasPermi="['resident:resident:export']">导出</el-button>
          <el-form-item label="服务包">
            <el-input v-model="userqueryParams.servicepackage" placeholder="请输入服务包" clearable
              @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="居民标签" style="width: 20%;">
            <el-select v-model="userqueryParams.userlabel" multiple placeholder="请选择">
              <el-option v-for="item in userlable" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item style="width: 20%;">
            <el-input v-model="userqueryParams.keyword" placeholder="请输入关键字" clearable @keyup.enter="handleQuery">
              <template #suffix>
                <el-button text style="padding: 0%;margin: 0;"> <template #icon>
                    <el-icon size="20">
                      <Search />
                    </el-icon>
                  </template></el-button>

              </template>

            </el-input>

          </el-form-item>
        </el-form>
        <el-table v-loading="loading" :data="residentList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="编号" align="center" prop="id" />
          <!-- <el-table-column label="姓名" align="center" prop="name" /> -->
          <el-table-column label="姓名" align="center" prop="name">
            <template #default="scope">
              <el-avatar shape="circle" size="small" :src="scope.row.avator"></el-avatar> {{ scope.row.name }}
            </template>
          </el-table-column>
          <!-- <el-table-column label="头像" align="center" prop="avator" /> -->
          <el-table-column label="身份证号" align="center" prop="idcard" />
          <!-- <el-table-column label="地址" align="center" prop="address" /> -->
          <!-- <el-table-column label="行政区域" align="center" prop="region" /> -->
          <!-- <el-table-column label="性别" align="center" prop="sex">
            <template #default="scope">
              <dict-tag :options="sys_user_sex" :value="scope.row.sex" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="生日" align="center" prop="birthday" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.birthday, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="籍贯" align="center" prop="place" /> -->
          <!-- <el-table-column label="民族" align="center" prop="ethnic" /> -->
          <!-- <el-table-column label="文化程度" align="center" prop="culture">
            <template #default="scope">
              <dict-tag :options="culture" :value="scope.row.culture" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="婚姻状况" align="center" prop="marry">
            <template #default="scope">
              <dict-tag :options="marry" :value="scope.row.marry" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="职业" align="center" prop="occupation" /> -->
          <!-- <el-table-column label="工作单位" align="center" prop="workplace" /> -->
          <!-- <el-table-column label="紧急联系人姓名" align="center" prop="urgent" /> -->
          <!-- <el-table-column label="紧急联系人电话" align="center" prop="urgenttel" /> -->
          <!-- <el-table-column label="户籍类型" align="center" prop="household">
            <template #default="scope">
              <dict-tag :options="household" :value="scope.row.household" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="费用类型" align="center" prop="expense">
            <template #default="scope">
              <dict-tag :options="expense" :value="scope.row.expense" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="定点医疗单位" align="center" prop="medicalunits" /> -->
          <!-- <el-table-column label="来源" align="center" prop="source">
            <template #default="scope">
              <dict-tag :options="source" :value="scope.row.source" />
            </template>
          </el-table-column> -->
          <!-- <el-table-column label="cm身高" align="center" prop="height" />
          <el-table-column label="kg体重" align="center" prop="weight" />
          <el-table-column label="血型" align="center" prop="blood" />
          <el-table-column label="RH阴性:是否 1是 0否" align="center" prop="RH" />
          <el-table-column label="过敏史" align="center" prop="allergies" />
          <el-table-column label="既往史" align="center" prop="past" />
          <el-table-column label="就诊史" align="center" prop="consultation" />
          <el-table-column label="家族史" align="center" prop="famliypast" />
          <el-table-column label="账号id可以为空" align="center" prop="sysUserId" />
          <el-table-column label="父id" align="center" prop="parent" />
          <el-table-column label="配偶id" align="center" prop="spouse" /> -->
          <el-table-column label="手机号" align="center" prop="tel" />
          <el-table-column label="签约状态" align="center">

            <template #default="scope">
              <el-tag type="success " v-if="scope.row.status == null">待签约</el-tag>
              <el-tag type="warning" v-else-if="scope.row.status == 1">签约中</el-tag>
              <el-tag type="danger" v-else-if="scope.row.status == 0">待续约</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="用户标签" align="center" width="300">
            <template #default="scope">
              <span v-for="item in scope.row.tags">
                <el-tag type="success">{{ item }}</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" icon="Operation" @click="detail(scope.row)"
                v-hasPermi="['resident:resident:list']">查看详情</el-button>
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"
                v-hasPermi="['resident:resident:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)"
                v-hasPermi="['resident:resident:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
          v-model:limit="queryParams.pageSize" @pagination="getList" />

        <!-- 添加或修改居民对话框 -->
        <el-dialog :title="title" v-model="open" width="1500px" append-to-body>
          <el-form ref="residentRef" :inline="true" :model="form" size="large" :rules="rules" label-width="150px">
            <el-form-item label="姓名" prop="name">
              <el-input v-model="form.name" placeholder="请输入姓名" />
            </el-form-item>
            <el-form-item label="头像" prop="avator">
              <el-input v-model="form.avator" placeholder="请输入头像" />
            </el-form-item>
            <el-form-item label="身份证号" prop="idcard">
              <el-input v-model="form.idcard" placeholder="请输入身份证号" />
            </el-form-item>
            <el-form-item label="手机号" prop="tel">
              <el-input v-model="form.tel" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="密码" prop="tel">
              <el-input v-model="password" type="password" placeholder="请输入密码" />
            </el-form-item>
            <el-form-item label="地址" prop="address">
              <el-input v-model="form.address" placeholder="请输入地址" />
            </el-form-item>
            <el-form-item label="行政区域" prop="region">
              <el-input v-model="form.region" placeholder="请输入行政区域" />
            </el-form-item>
            <el-form-item label="性别" prop="sex" class="w200">
              <el-select v-model="form.sex" placeholder="请选择性别">
                <el-option v-for="dict in sys_user_sex" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="生日" prop="birthday">
              <el-date-picker clearable v-model="form.birthday" type="date" value-format="YYYY-MM-DD"
                placeholder="请选择生日">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="籍贯" prop="place">
              <el-input v-model="form.place" placeholder="请输入籍贯" />
            </el-form-item>
            <el-form-item label="文化程度" prop="culture" class="w200">
              <el-select v-model="form.culture" placeholder="请选择文化程度">
                <el-option v-for="dict in culture" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="婚姻状况" prop="marry" class="w200">
              <el-select v-model="form.marry" placeholder="请选择婚姻状况">
                <el-option v-for="dict in marry" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="职业" prop="occupation">
              <el-input v-model="form.occupation" placeholder="请输入职业" />
            </el-form-item>
            <el-form-item label="工作单位" prop="workplace">
              <el-input v-model="form.workplace" placeholder="请输入工作单位" />
            </el-form-item>
            <el-form-item label="紧急联系人姓名" prop="urgent">
              <el-input v-model="form.urgent" placeholder="请输入紧急联系人姓名" />
            </el-form-item>
            <el-form-item label="紧急联系人电话" prop="urgenttel">
              <el-input v-model="form.urgenttel" placeholder="请输入紧急联系人电话" />
            </el-form-item>
            <el-form-item label="户籍类型" prop="household" class="w200">
              <el-select v-model="form.household" placeholder="请选择">
                <el-option v-for="dict in household" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="费用类型" prop="expense" class="w200">
              <el-select v-model="form.expense" placeholder="请选择费用类型">
                <el-option v-for="dict in expense" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="定点医疗单位" prop="medicalunits">
              <el-input v-model="form.medicalunits" placeholder="请输入定点医疗单位" />
            </el-form-item>
            <el-form-item label="来源" prop="source" class="w200 ">
              <el-select v-model="form.source" placeholder="请选择来源">
                <el-option v-for="dict in source" :key="dict.value" :label="dict.label"
                  :value="parseInt(dict.value)"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="cm身高" prop="height">
              <el-input v-model="form.height" placeholder="请输入cm身高" />
            </el-form-item>
            <el-form-item label="kg体重" prop="weight">
              <el-input v-model="form.weight" placeholder="请输入kg体重" />
            </el-form-item>
            <el-form-item label="血型" prop="blood">
              <el-input v-model="form.blood" placeholder="请输入血型" />
            </el-form-item>
            <el-form-item label="RH" prop="RH" class="w200">
              <el-select v-model="form.RH" placeholder="请选择" clearable>
                <el-option v-for="item in RHoptions" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="过敏史" prop="allergies">
              <el-input v-model="form.allergies" placeholder="请输入过敏史" />
            </el-form-item>
            <el-form-item label="既往史" prop="past">
              <el-input v-model="form.past" placeholder="请输入既往史" />
            </el-form-item>
            <el-form-item label="就诊史" prop="consultation">
              <el-input v-model="form.consultation" placeholder="请输入就诊史" />
            </el-form-item>
            <el-form-item label="家族史" prop="famliypast">
              <el-input v-model="form.famliypast" placeholder="请输入家族史" />
            </el-form-item>
            <el-form-item label="账号id可以为空" prop="sysUserId">
              <el-input v-model="form.sysUserId" placeholder="请输入账号id可以为空" />
            </el-form-item>
            <el-form-item label="父id" prop="parent">
              <el-input v-model="form.parent" placeholder="请输入父id" />
            </el-form-item>
            <el-form-item label="配偶id" prop="spouse">
              <el-input v-model="form.spouse" placeholder="请输入配偶id" />
            </el-form-item>
            <!-- <el-form-item label="用户标签">
              <el-select v-model="selectuserlable" multiple placeholder="请选择标签" clearable>
                <el-option v-for="item in userlable" :key="item.value" :label="item.label"
                  :value="item.value"></el-option>
              </el-select>
            </el-form-item> -->
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button type="primary" @click="submitForm">确 定</el-button>
              <el-button @click="cancel">取 消</el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup name="Resident">
import { useRouter } from "vue-router";
//查询模版

const router = useRouter();
//查看详情
function detail(row) {

  router.push({ path: "residentdetail", query: row });
}
//密码
const password = ref('')
//Rh
const RHoptions = [
  { value: "1", label: "否" },
  { value: "0", label: "是" },
  { value: "2", label: "未知" },
]
import { ElMessage } from "element-plus";
import { ref } from "vue";
// 筛选条件
let userqueryParams = ref({
  status: "",
  institution: "",
  team: "",
  servicepackage: "",
  userlabel: [],
  keyword: "",
});
let selectuserlable = ref([])
// 用户标签
let userlable = ref([])
//得到标签
function getlable() {
  getlablelist().then(response => {
    console.log(response.data);
    response.data.forEach(item => {
      userlable.value.push({ value: item.id, label: item.tagName })

    })
  })

}
// 签约状态
let status = [
  { value: "1", label: "待签约" },
  { value: "2", label: "签约中" },
  { value: "3", label: "签约生效中" },
  { value: "4", label: "待续约" },
];
// 签约机构
let institution = ref([])
//按下回车查询
const residenhandleQuery = () => {
  ElMessage({
    message: "enter查询中...",
    type: "info",
  })
  getList()
}
// 查询
function residentgetList() {
  ElMessage({
    message: "查询中...",
    type: "info",
  });

}




//yuan
import { settag, getlablelist, listResidentfirst, listResident, getResident, delResident, addResident, updateResident } from "@/api/resident/resident";
import { resetUserPwd, getUser, updateUser, addUser } from "@/api/system/user";
const { proxy } = getCurrentInstance();
const { household, marry, expense, sys_user_sex, culture, source } = proxy.useDict('marry', 'expense', 'sys_user_sex', 'culture', 'source', 'household');
//查询模版
let sysuser = ref({})
function getsysuser() {
  getUser(104).then(response => {
    console.log("getsysuser", response);
    sysuser.value = response.data;
    sysuser.value.roleIds = [100]
    console.log("sysuser", sysuser.value);

  })
}
const residentList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    avator: null,
    idcard: null,
    address: null,
    region: null,
    sex: null,
    birthday: null,
    place: null,
    ethnic: null,
    culture: null,
    marry: null,
    occupation: null,
    workplace: null,
    urgent: null,
    urgenttel: null,
    household: null,
    expense: null,
    medicalunits: null,
    source: null,
    height: null,
    weight: null,
    blood: null,
    RH: null,
    allergies: null,
    past: null,
    consultation: null,
    famliypast: null,
    sysUserId: null,
    parent: null,
    spouse: null,
    tel: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询居民列表 */
function getList() {
  loading.value = true;
  listResidentfirst(queryParams.value).then(response => {
    console.log('response.rows', response.rows);
    residentList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    avator: null,
    idcard: null,
    address: null,
    region: null,
    sex: null,
    birthday: null,
    place: null,
    ethnic: null,
    culture: null,
    marry: null,
    occupation: null,
    workplace: null,
    urgent: null,
    urgenttel: null,
    household: null,
    expense: null,
    medicalunits: null,
    source: null,
    height: null,
    weight: null,
    blood: null,
    RH: null,
    allergies: null,
    past: null,
    consultation: null,
    famliypast: null,
    sysUserId: null,
    parent: null,
    spouse: null,
    tel: null
  };
  proxy.resetForm("residentRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加居民";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getResident(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改居民";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["residentRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        sysuser.value.userId = form.value.sysUserId
        sysuser.value.userName = form.value.tel
        sysuser.value.nickName = form.value.name
        sysuser.value.password = undefined
        sysuser.value.phonenumber = form.value.tel
        sysuser.value.email = undefined
        console.log('sysuseradd', sysuser.value);

        updateUser(sysuser.value).then(response => {
          proxy.$modal.msgSuccess("系统用户修改成功");
          resetUserPwd(form.value.sysUserId, password.value).then(response => {
            proxy.$modal.msgSuccess("修改成功，新密码是：" + response.data);
            updateResident(form.value).then(response => {
              proxy.$modal.msgSuccess("home修改成功");
              open.value = false;
              getList();
            });

          });

        }).catch(error => {
          console.log('error', error);
          proxy.$modal.msgError("系统用户修改失败");
        })

      } else {
        sysuser.value.userId = undefined
        sysuser.value.userName = form.value.tel
        sysuser.value.nickName = form.value.name
        sysuser.value.password = password.value
        sysuser.value.phonenumber = form.value.tel
        sysuser.value.email = undefined
        console.log('sysuseradd', sysuser.value);
        addUser(sysuser.value).then(res => {
          proxy.$modal.msgSuccess("新增成功");
          console.log('res.data', res.data);
          form.value.sysUserId = res.data
          addResident(form.value).then(response => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          }).catch(error => {
            proxy.$modal.msgError(error.message);
          });
        }).catch(error => {
          proxy.$modal.msgError(error.message);
        })

      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除居民编号为"' + _ids + '"的数据项？').then(function () {

    return delResident(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('resident/resident/export', {
    ...queryParams.value
  }, `resident_${new Date().getTime()}.xlsx`)
}
getsysuser();
getlable();
getList();
</script>
<style scoped>
.cardbg {
  width: 100%;
  height: 100%;
  background-color: #f2f7fb;
  display: flex;
  justify-content: center;
  align-items: center;
}

.card {
  /* 圆角 */
  border-radius: 10px;
  width: 80%;
  height: 100%;
  background-color: white;
  padding: 20px;
}

.w100 {
  width: 100px;
}

.w200 {
  width: 300px;
}
</style>
